'''
Created on Nov 13, 2013

@author: haind
'''
from database import cache
import threading
import json
import time
import CONSTANTS

class PSListener(threading.Thread):
    '''
    1 thread, listen to @channels from @redissv
    then dispatch to worker
    '''
#------------------------------------------------------------------------------ 
    def __init__(self, channels, sleep_time):
        threading.Thread.__init__(self)
        self.re_server = cache()._re_server.re_sv
        self.local_redis = cache()._re_local.re_lc
        self.pubsub = self.re_server.pubsub()
        self.pubsub.subscribe(channels)
#         self.pubsub_local = self.local_redis.pubsub()
#         self.pubsub_local.subscribe(channels)
        self.sleep_time = sleep_time
#------------------------------------------------------------------------------ 
    def work(self, item):
        v_task = self.re_server.get(item['data'])
        if v_task:
            self.re_server.zrem('flag' + item['channel'][7:], item['data'])
            self.re_server.setex(item['data'], v_task, 60)
            data = {'job':item['channel'][8:], 'params': json.loads(v_task)}
            if data['params'].has_key('token') and data['params'].get('token') == '':
                return
            print data
            self.local_redis.rpush(CONSTANTS.LOCAL_RD.TASKS, data)
            
#         v_task1 = self.local_redis.get(item['data'])
#         if v_task1:
# #             self.local_redis.zrem('flag' + item['channel'][7:], item['data'])
# #             self.local_redis.setex(item['data'], v_task1, 60)
#             print 'dispatcher:', v_task1
#             data = {'job':item['channel'][8:], 'params': json.loads(v_task1)}
#             self.local_redis.rpush(CONSTANTS.LOCAL_RD.TASKS, data)
#------------------------------------------------------------------------------ 
    def run(self):
        for item in self.pubsub.listen():
            self.work(item)
            time.sleep(self.sleep_time)
#------------------------------------------------------------------------------ 
if __name__ == "__main__":
    a = PSListener(['channel:ionline:login', 'channel:ionline:logout'], 0)
    print a.is_alive()